// pages/myZhiBo/myZhiBo.js
var Session = require('../../vendor/qcloud-weapp-client-sdk/lib/session.js');
var config = require('../../config.js');
var commons = require('../../commons.js');
var qcloud = require('../../vendor/qcloud-weapp-client-sdk/index');
var register = require('../../template/register/register.js');
var utils = require('../../vendor/qcloud-weapp-client-sdk/lib/utils.js');
var index = {

  /**
   * 页面的初始数据
   */
  data: {
    date: '',
    time: '',
    isShow: true,
    imgUpData: "", //背景图
    titleData: '', //标题
    commentTxt: '', //直播内容
    typeData: '0', //横竖屏
    actionShow: 0, //选择音频还是视频
    user_status: '',
    rtmpUrl: "",
    copyUrlShow: false, //隐藏复制弹出窗口
    detailID: 0,
    navList: [], //分类
    navindex: 0, //分类
    navCutId: "", //分类id
    navListData: [], //分类
    ypAcitonData: [{
      "iconSa": '../../images/icon/spiconaction.png',
      "iconSb": "../../images/icon/spicon.png",
      "icontitle": "视频",
    }, {
      "iconSa": '../../images/icon/yyiconaction.png',
      "iconSb": "../../images/icon/yyicona.png",
      "icontitle": "语音",
    }],
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var date = new Date();
    var y = 1900 + date.getYear();
    var m = "0" + (date.getMonth() + 1);
    var d = "0" + date.getDate();
    var timea = y + "-" + m.substring(m.length - 2, m.length) + "-" + d.substring(d.length - 2, d.length);
    var minuts = date.getMinutes(); //获取当前时间(从1970.1.1开始的毫秒数)
    var hours = date.getHours(); //获取当前小时数(0-23)
    if (minuts < 10) {
      minuts = "0" + minuts;
    }
    var timeb = hours + ":" + minuts;
    this.setData({
      date: timea,
      time: timeb,
      // detailID: options.detailID,
      // dataTime: Date.parse(new Date()) / 1000,
      is_verified: Session.get().userInfo.is_verified
    })
    this.indexCat();

  },
  //选择直播类型
  clickActonZb: function(e) {
    var id = e.currentTarget.id;
    this.setData({
      actionShow: id
    })
  },
  //选择时间
  bindDateChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value,
    })
  },
  bindTimeChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      time: e.detail.value,
    })
  },
  // 选择分类
  navListClick: function(e) {
    console.log('分类为', e.detail.value)
    this.setData({
      navindex: e.detail.value,
      navCutId: this.data.navListData[e.detail.value].cat_id
    })
  },
  //选择横竖屏
  // switch1Change: function(e) {
  //   var sctrue = e.detail.value;
  //   var is_search = 0;
  //   var that = this;
  //   if (sctrue) {
  //     is_search = 1;
  //     wx.showToast({
  //       title: '已开启横屏',
  //       icon: 'none',
  //     })
  //   } else {
  //     is_search = 0;
  //     wx.showToast({
  //       title: '已关闭横屏',
  //       icon: 'none',
  //     })
  //   }
  //   // console.log('switch1 发生 change 事件，携带值为', e.detail.value)
  // },
  //直播简介内容
  bindTextAreaBlur: function(e) {
    // console.log(e.detail.value)
    this.setData({
      commentTxt: e.detail.value
    })
  },
  //上传图片
  imgClickUp: function() {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: 'https://live.xiaochengshi.net/Api/Index/UploadFiles', //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            'user': 'test'
          },
          success(res) {
            var imgD = JSON.parse(res.data);
            that.setData({
              imgUpData: imgD.data
            })
            //do something
          }
        })
      }
    })
  },
  //输入标题
  bindKeyInput: function(e) {
    this.setData({
      titleData: e.detail.value
    })
  },
  //提交直播
  subAddZhiBo: function() {
    var that = this;
    var dateall = this.data.date + " " + this.data.time;
    var dataTimeAll = new Date(dateall.replace(/-/g, '/')).getTime();
    var dataTime = dataTimeAll / 1000;
    console.log("时间形式是:" + dateall + ";" + "时间戳是：" + dataTime)
    var timestamp = Date.parse(new Date()) / 1000;
    if (timestamp > dataTime) {
      console.log(timestamp, dataTime)
      utils.showError('请选择正确时间')
    } else if (this.data.dataTime == '') {
      utils.showError('请选择开始时间')
    } else if (this.data.titleData == '') {
      utils.showError('请输入标题')
    } else if (this.data.commentTxt == '') {
      utils.showError('请输入内容')
    } else if (this.data.navCutId == '') {
      utils.showError('请选择分类')
    } else {
      qcloud.request({
        login: true,
        url: config.service.liveAddUrl,
        data: {
          type: this.data.actionShow,
          stime: dataTime,
          thumb: this.data.imgUpData,
          title: this.data.titleData,
          content: this.data.commentTxt,
          cat_id: this.data.navCutId
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success: function(res) {
          // console.log(res)
          if (res.data.data.code == 0) {
            wx.showModal({
              title: '提示',
              content: '您还没有认证！是否提交个人认证',
              success(res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '../iPhone/iPhone',
                  })
                } else if (res.cancel) {
                  console.log('取消创建')
                }
              }
            })
          } else if (res.data.data.code == 1) {
            // utils.showError('创建成功,审核通过后可在我的视频列表进行直播')
            that.setData({
              rtmpUrl: res.data.msg,
              isShow: false,
              copyUrlShow: true
            })

          } else if (res.data.data.code == 2) {
            wx.showModal({
              title: '您没有权限，请联系官方创建',
              content: '0512-63971181',
              success(res) {
                if (res.confirm) {
                  wx.makePhoneCall({
                    phoneNumber: '0512-63971181' //仅为示例，并非真实的电话号码
                  })
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })

          } else {
            utils.showError("创建失败")
          }
        },
        fail: function(res) {
          utils.showError(res.message)
        },
        complete: function() {
          setTimeout(function() {
            wx.hideLoading();
            wx.stopPullDownRefresh();
          }, 500)
        }
      });
    }

  },
  //分类拉取
  indexCat: function() {
    var that = this;
    qcloud.request({
      login: false,
      url: config.service.indexCatUrl,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function(res) {
        var arr = [];
        for (let i = 0; i < res.data.data.length; i++) {
          arr.push(res.data.data[i].cat_title);
        }
        that.setData({
          navList: arr,
          navCutId: res.data.data[0].cat_id,
          navListData: res.data.data
        });

      },
      fail: function(res) {
        utils.showError(res.message)
      },
      complete: function() {}
    });

  },
  // 复制粘贴
  copyTBL: function(e) {
    var self = this;
    wx.setClipboardData({
      data: self.data.rtmpUrl,
      success: function(res) {
        // self.setData({copyTip:true}),
        utils.showError("复制成功");
        self.setData({
          isShow: true,
          copyUrlShow: false
        })
        setTimeout(function() {
          // 跳转直播页面
          wx.redirectTo({
            url: '../push/index',
          })
        }, 500)
      }
    });
  },
  sureBtn: function() {
    this.setData({
      copyUrlShow: false
    });
    wx.switchTab({
      url: '../user/user',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '小城市live',
      path: '/pages/index/index',
      success: function () {
        utils.showSuccess("转发成功");
      }
    };
  }
};
var data = Object.assign(index.data, register.data);
var page = Object.assign(index, register);
page.data = data;
Page(page);